var express = require('express');
var router = express.Router();

var multiparty = require('multiparty');

var pathViews = __dirname.substring(0, __dirname.lastIndexOf('\\')) + '/views/';

var fs = require('fs');

router.get('/', function(req, res){
    res.sendFile(pathViews + 'index.html'); // 要求我们新建这个网页
});

router.post('/', function(req, res){
    var form = new multiparty.Form();

    form.encoding = 'utf-8';
    form.uploadDir = './public/files';
    form.maxFileSize = 20 * 1024 * 1024;

    form.parse(req, function(err, fields, files){
        // var filesTemp = JSON.stringify(files, null, 2);
        // var fieldsTemp = JSON.stringify()

        // console.log(fields);
        // console.log(files);


        if(err) throw err;

        var inputFile = files.uploadFile[0];
        var uploadedPath = inputFile.path;

        var destPath = './public/files/' + inputFile.originalFilename;

        fs.rename(uploadedPath, destPath, (err)=>{
            if(err)throw err;
        });

        res.end();

    });

});

module.exports = router;